
#import "KrVideoPlayerController.h"
#import <AVFoundation/AVFoundation.h>


static const CGFloat kVideoPlayerControllerAnimationTimeinterval = 0.3f;

@interface KrVideoPlayerController()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong) UIView *movieBackgroundView;
@property (nonatomic, assign) CGRect originFrame;
@property (nonatomic, strong) NSTimer *durationTimer;
@property (nonatomic, strong) UITableView *videoListTableView;

@property (nonatomic, strong) HomeModel *data;
@property (nonatomic, strong) NSArray *dataArr;


@end

@implementation KrVideoPlayerController

- (void)dealloc
{
    [self cancelObserver];
}

- (instancetype)initWithFrame:(CGRect)frame data:(NSArray *)dataArr index:(NSInteger)index
{
    self = [super init];
    if (self)
    {
        self.data = dataArr[index];
        self.dataArr=dataArr;
        self.view.frame = frame;
        self.view.backgroundColor = [UIColor blackColor];
        self.controlStyle = MPMovieControlStyleNone;//不使用系统的进度条
        [self.view addSubview:self.videoControl];
        self.videoControl.frame = self.view.bounds;
        self.videoControl.titleLabel.text = self.data.title;
        [self configObserver];//设置观察者
        [self configControlAction];
        [self ListeningRotating];//监听设备旋转方向
        [self setup_videoListTableView];
    }
    return self;
}

-(void)setup_videoListTableView
{
    _videoListTableView=[[UITableView alloc]initWithFrame:CGRectMake(PhoneScreen_HEIGHT, 0, 200, CGRectGetWidth(self.view.bounds)) style:UITableViewStylePlain];
    _videoListTableView.dataSource=self;
    _videoListTableView.delegate=self;
    _videoListTableView.bounces=NO;//回弹效果
    _videoListTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;//分割线样式
    _videoListTableView.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:.3];
    [self.view addSubview:_videoListTableView];
}

#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* cellID=@"cell";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }

    cell.backgroundColor=[UIColor clearColor];
    self.data=self.dataArr[indexPath.row];
    cell.textLabel.text=self.data.title;
    cell.textLabel.font=[UIFont systemFontOfSize:15];
    cell.textLabel.textColor=[UIColor whiteColor];

    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeModel *model=self.dataArr[indexPath.row];
    self.contentURL=[NSURL URLWithString:model.video_url];
    self.videoControl.titleLabel.text = model.title;
    [self prepareToPlay];
    [self play];
    
    self.videoControl.videoListBtn.userInteractionEnabled=YES;
    [UIView animateWithDuration:.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.videoListTableView.left=self.videoListTableView.left+200;
    } completion:^(BOOL finished) {
        
    }];
    
}




#pragma mark - Override Method

- (void)setContentURL:(NSURL *)contentURL
{
    [self stop];
    [super setContentURL:contentURL];//MPMoviePlayerController的方法
//    [self play];
}

#pragma mark - Public Method 公共方法

//把self.view加到window上
- (void)showInWindow
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    if (!keyWindow) {
        keyWindow = [[[UIApplication sharedApplication] windows] firstObject];
    }
    [keyWindow addSubview:self.view];
    //出现播放器的动画
    self.view.alpha = 0.0;
    [UIView animateWithDuration:kVideoPlayerControllerAnimationTimeinterval animations:^{
        self.view.alpha = 1.0;
    } completion:^(BOOL finished) {
        
    }];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];//淡入淡出隐藏状态栏
}

- (void)dismiss
{
    [self stopDurationTimer];//关闭定时器
    [self stop];//停止方法
    [UIView animateWithDuration:kVideoPlayerControllerAnimationTimeinterval animations:^{
        self.view.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        if (self.dimissCompleteBlock) {
            self.dimissCompleteBlock();
        }
    }];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
}

- (void)setIsFullscreenMode:(BOOL)isFullscreenMode//全屏显示时的设置
{
    _isFullscreenMode = isFullscreenMode;
    
    self.videoControl.topBar.hidden = !isFullscreenMode;
    self.videoControl.liangduMove.hidden = !isFullscreenMode;
    self.videoControl.shengyiMove.hidden = !isFullscreenMode;
    self.videoControl.showDefinitionView.hidden = !isFullscreenMode;
    self.videoControl.definitionView.hidden = !isFullscreenMode;
}

#pragma mark - Private Method 私有方法

//设置观察者
- (void)configObserver
{
    //播放状态改变时，配合playbackState获取具体状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMoviePlayerPlaybackStateDidChangeNotification) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    //网络加载状态改变时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMoviePlayerLoadStateDidChangeNotification) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
    //当准备状态改变时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMoviePlayerReadyForDisplayDidChangeNotification) name:MPMoviePlayerReadyForDisplayDidChangeNotification object:nil];
    //确定播放音频的时长
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMPMovieDurationAvailableNotification) name:MPMovieDurationAvailableNotification object:nil];
    //当用户退出视频时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackDidFinish) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

- (void)cancelObserver//移除观察者
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)configControlAction//设置界面功能
{
    [self.videoControl.playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.pauseButton addTarget:self action:@selector(pauseButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.closeButton addTarget:self action:@selector(shrinkScreenButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.fullScreenButton addTarget:self action:@selector(fullScreenButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.shrinkScreenButton addTarget:self action:@selector(shrinkScreenButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchBegan:) forControlEvents:UIControlEventTouchDown];
    [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchEnded:) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.progressSlider addTarget:self action:@selector(progressSliderTouchEnded:) forControlEvents:UIControlEventTouchUpOutside];
    [self.videoControl.showDefinitionView addTarget:self action:@selector(showDefinitionViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.biaoqingBtn addTarget:self action:@selector(definitionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.gaoqingBtn addTarget:self action:@selector(definitionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.videoControl.videoListBtn addTarget:self action:@selector(showVideoList:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    [self setProgressSliderMaxMinValues];//设置滑动器
    [self monitorVideoPlayback];//给显示时间控件赋值并保存时间
}

- (void)onMPMoviePlayerPlaybackStateDidChangeNotification
{
    if (self.playbackState == MPMoviePlaybackStatePlaying) {//正在播放
        self.videoControl.pauseButton.hidden = NO;
        self.videoControl.playButton.hidden = YES;
        [self startDurationTimer];//开启定时器
        [self.videoControl.indicatorView stopAnimating];
        [self.videoControl autoFadeOutControlBar];
    } else {
        self.videoControl.pauseButton.hidden = YES;
        self.videoControl.playButton.hidden = NO;
        [self stopDurationTimer];//关闭定时器
        if (self.playbackState == MPMoviePlaybackStateStopped) {
            [self.videoControl animateShow];
        }
    }
}

- (void)onMPMoviePlayerLoadStateDidChangeNotification
{
    if (self.loadState & MPMovieLoadStateStalled) {//缓冲中
        [self.videoControl.indicatorView startAnimating];                 //
    }
}

- (void)onMPMoviePlayerReadyForDisplayDidChangeNotification
{
    
}

- (void)onMPMovieDurationAvailableNotification//播放音频的时长
{
    [self setProgressSliderMaxMinValues];
}

- (void)moviePlayerPlaybackDidFinish//用户退出视频
{
    if (self.playCompleteBlock)
    {
        self.playCompleteBlock();
    }
}

- (void)playButtonClick//播放
{
    [self play];
    self.videoControl.playButton.hidden = YES;
    self.videoControl.pauseButton.hidden = NO;
}

- (void)pauseButtonClick//暂停
{
    [self pause];
    self.videoControl.playButton.hidden = NO;
    self.videoControl.pauseButton.hidden = YES;
}

- (void)closeButtonClick//关闭
{
    [self dismiss];
}

- (void)fullScreenButtonClick//全屏
{
    if (self.isFullscreenMode) {
        return;
    }
    [self setDeviceOrientationLandscapeRight];
}
- (void)shrinkScreenButtonClick//返回最小屏幕
{
    if (!self.isFullscreenMode) {
        return;
    }
    
    [self backOrientationPortrait];
    
}

//唤出切换清晰度视图
- (void)showDefinitionViewButtonClick:(UIButton *)button
{
    if (!button.selected) {
        
        [UIView animateWithDuration:.3 animations:^{
            
            self.videoControl.definitionView.alpha=1;
        }];
    }else{
        
        [UIView animateWithDuration:.3 animations:^{
            
            self.videoControl.definitionView.alpha=0;
        }];
    }
    
    button.selected = !button.selected;
}

//标清、高清按钮触发事件
-(void)definitionBtnClick:(UIButton*)button
{
    self.videoControl.showDefinitionView.selected=NO;
    
    if (button.selected) {
        [UIView animateWithDuration:.3 animations:^{
            self.videoControl.definitionView.alpha=0;
        }];
        return;
    }
    
    button.selected = !button.selected;
    

//    NSURL *playURL;
//    NSTimeInterval time = self.currentPlaybackTime;
    
    if (button.isSelected && [button.currentTitle isEqualToString:@"标清"])
    {
        self.videoControl.gaoqingBtn.selected=NO;
        
        
//        playURL = [NSURL URLWithString:self.data.video_url];//播放地址

        [self.videoControl.showDefinitionView setTitle:button.currentTitle forState:UIControlStateNormal];
        [self.videoControl.showDefinitionView setTitle:button.currentTitle forState:UIControlStateSelected];
        
    }
    else if (button.isSelected && [button.currentTitle isEqualToString:@"高清"])
    {
        self.videoControl.biaoqingBtn.selected=NO;
        
        
        [self.videoControl.showDefinitionView setTitle:button.currentTitle forState:UIControlStateNormal];
        [self.videoControl.showDefinitionView setTitle:button.currentTitle forState:UIControlStateSelected];
        
    }
    
    [UIView animateWithDuration:.3 animations:^{
        self.videoControl.definitionView.alpha=0;
    }];

//    self.contentURL = playURL;
//    
//    
//    self.currentPlaybackTime = time;
//    self.initialPlaybackTime = time;//起始播放时间
//    
//    [self prepareToPlay];
    
}

-(void)showVideoList:(UIButton*)button
{
    self.videoControl.videoListBtn.userInteractionEnabled=NO;
    [UIView animateWithDuration:.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.videoListTableView.left=self.videoListTableView.left-200;
    } completion:^(BOOL finished) {
        
    }];
}

-(void)downloadBtnClick:(UIButton*)button
{
    button.selected=YES;
}

#pragma mark - 下载



#pragma mark -- 设备旋转监听 改变视频全屏状态显示方向 --
//监听设备旋转方向
- (void)ListeningRotating{
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onDeviceOrientationChange)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil
     ];
    
}
- (void)onDeviceOrientationChange{
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;//设置方向
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;//界面方向
    switch (interfaceOrientation) {
            /**        case UIInterfaceOrientationUnknown:
             NSLog(@"未知方向");
             break;
             */
        case UIInterfaceOrientationPortraitUpsideDown:{
            NSLog(@"第3个旋转方向---电池栏在下");
            [self backOrientationPortrait];
        }
            break;
        case UIInterfaceOrientationPortrait:{
            NSLog(@"第0个旋转方向---电池栏在上");
            [self backOrientationPortrait];
        }
            break;
        case UIInterfaceOrientationLandscapeLeft:{
            NSLog(@"第2个旋转方向---电池栏在右");
            
            [self setDeviceOrientationLandscapeLeft];
        }
            break;
        case UIInterfaceOrientationLandscapeRight:{
            
            NSLog(@"第1个旋转方向---电池栏在左");
            
            [self setDeviceOrientationLandscapeRight];
            
        }
            break;
            
        default:
            break;
    }
    
}
//返回小屏幕
- (void)backOrientationPortrait{
    if (!self.isFullscreenMode) {
        return;
    }
    [UIView animateWithDuration:0.3f animations:^{
        [self.view setTransform:CGAffineTransformIdentity];
        self.frame = self.originFrame;
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    } completion:^(BOOL finished) {
        self.isFullscreenMode = NO;
        self.videoControl.fullScreenButton.hidden = NO;
        self.videoControl.shrinkScreenButton.hidden = YES;
        if (self.willBackOrientationPortrait) {
            self.willBackOrientationPortrait();
        }
    }];
}

//电池栏在左全屏
- (void)setDeviceOrientationLandscapeRight{
    
    //    if (self.integer==2) {
    //        self.originFrame = self.view.frame;
    //        CGFloat height = [[UIScreen mainScreen] bounds].size.width;
    //        CGFloat width = [[UIScreen mainScreen] bounds].size.height;
    //        CGRect frame = CGRectMake((height - width) / 2, (width - height) / 2, width, height);;
    //        [UIView animateWithDuration:0.3f animations:^{
    //            self.frame = frame;
    //            [self.view setTransform:CGAffineTransformMakeRotation(M_PI)];
    //        } completion:^(BOOL finished) {
    //            self.integer = 1;
    //            self.isFullscreenMode = YES;
    //            self.videoControl.fullScreenButton.hidden = YES;
    //            self.videoControl.shrinkScreenButton.hidden = NO;
    //        }];
    //    }
    if (self.isFullscreenMode) {
        return;
    }
    
    self.originFrame = self.view.frame;
    CGFloat height = [[UIScreen mainScreen] bounds].size.width;
    CGFloat width = [[UIScreen mainScreen] bounds].size.height;
    CGRect frame = CGRectMake((height - width) / 2, (width - height) / 2, width, height);;
    [UIView animateWithDuration:0.3f animations:^{
        self.frame = frame;
        [self.view setTransform:CGAffineTransformMakeRotation(M_PI_2)];//旋转
    } completion:^(BOOL finished) {
        self.isFullscreenMode = YES;
        self.videoControl.fullScreenButton.hidden = YES;
        self.videoControl.shrinkScreenButton.hidden = NO;
        if (self.willChangeToFullscreenMode) {
            self.willChangeToFullscreenMode();
        }
    }];
    
}
//电池栏在右全屏
- (void)setDeviceOrientationLandscapeLeft{
    
    //    if  (self.integer==1){
    //        self.originFrame = self.view.frame;
    //        CGFloat height = [[UIScreen mainScreen] bounds].size.width;
    //        CGFloat width = [[UIScreen mainScreen] bounds].size.height;
    //        CGRect frame = CGRectMake((height - width) / 2, (width - height) / 2, width, height);;
    //        [UIView animateWithDuration:0.3f animations:^{
    //            self.frame = frame;
    //            [self.view setTransform:CGAffineTransformMakeRotation(-M_PI)];
    //        } completion:^(BOOL finished) {
    //            self.integer = 2;
    //            self.isFullscreenMode = YES;
    //            self.videoControl.fullScreenButton.hidden = YES;
    //            self.videoControl.shrinkScreenButton.hidden = NO;
    //        }];
    //    }
    if (self.isFullscreenMode) {
        return;
    }
    self.originFrame = self.view.frame;
    CGFloat height = [[UIScreen mainScreen] bounds].size.width;
    CGFloat width = [[UIScreen mainScreen] bounds].size.height;
    CGRect frame = CGRectMake((height - width) / 2, (width - height) / 2, width, height);;
    [UIView animateWithDuration:0.3f animations:^{
        self.frame = frame;
        [self.view setTransform:CGAffineTransformMakeRotation(-M_PI_2)];
    } completion:^(BOOL finished) {
        self.isFullscreenMode = YES;
        self.videoControl.fullScreenButton.hidden = YES;
        self.videoControl.shrinkScreenButton.hidden = NO;
        if (self.willChangeToFullscreenMode) {
            self.willChangeToFullscreenMode();
        }
    }];
}

- (void)setProgressSliderMaxMinValues {
    CGFloat duration = self.duration;//媒体时长
    self.videoControl.progressSlider.minimumValue = 0.f;
    self.videoControl.progressSlider.maximumValue = duration;
}

- (void)progressSliderTouchBegan:(UISlider *)slider {//touchdown
    [self pause];
    [self.videoControl cancelAutoFadeOutControlBar];//取消自动淡出控制栏
}

- (void)progressSliderTouchEnded:(UISlider *)slider {//touchupinside
    [self setCurrentPlaybackTime:floor(slider.value)];//改变当前播放时间
    [self play];
    [self.videoControl autoFadeOutControlBar];
}

- (void)progressSliderValueChanged:(UISlider *)slider {//值改变
    double currentTime = floor(slider.value);
    double totalTime = floor(self.duration);
    [self setTimeLabelValues:currentTime totalTime:totalTime];
}

- (void)monitorVideoPlayback
{
    double currentTime = floor(self.currentPlaybackTime);//当前播放时间 秒
    double totalTime = floor(self.duration);//floor：如果参数是小数，则求最大的整数但不大于本身.
    [self setTimeLabelValues:currentTime totalTime:totalTime];
    self.videoControl.progressSlider.value = ceil(currentTime);
}

//给显示时间控件赋值并保存时间
- (void)setTimeLabelValues:(double)currentTime totalTime:(double)totalTime
{
    //消逝的分钟
    double minutesElapsed = floor(currentTime / 60.0);//分钟
    //消逝的秒钟
    double secondsElapsed = fmod(currentTime, 60.0);//计算currentTime除以60.0的余数
    NSString *timeElapsedString = [NSString stringWithFormat:@"%02.0f:%02.0f", minutesElapsed, secondsElapsed];
    
    double minutesRemaining = floor(totalTime / 60.0);;
    double secondsRemaining = floor(fmod(totalTime, 60.0));;
    NSString *timeRmainingString = [NSString stringWithFormat:@"%02.0f:%02.0f", minutesRemaining, secondsRemaining];
    
    self.videoControl.timeLabel.text = timeElapsedString;
    self.videoControl.timeAllLabel.text = timeRmainingString;
    
//    [self.fmdbObject watchSaveData:self.data time:String((NSInteger)currentTime) finish:nil];//只有这一处使用了fmdb 记录播放的时间         转成字符串
    
}

- (void)startDurationTimer
{
    self.durationTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(monitorVideoPlayback) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.durationTimer forMode:NSDefaultRunLoopMode];
}

- (void)stopDurationTimer
{
    [self.durationTimer invalidate];
}

- (void)fadeDismissControl
{
    [self.videoControl animateHide];//动态隐藏
}

#pragma mark - Property

- (KrVideoPlayerControlView *)videoControl
{
    if (!_videoControl) {
        _videoControl = [[KrVideoPlayerControlView alloc] init];
    }
    return _videoControl;
}

- (UIView *)movieBackgroundView
{
    if (!_movieBackgroundView) {
        _movieBackgroundView = [UIView new];
        _movieBackgroundView.alpha = 0.0;
        _movieBackgroundView.backgroundColor = [UIColor blackColor];
    }
    return _movieBackgroundView;
}

//设置frame
- (void)setFrame:(CGRect)frame
{
    [self.view setFrame:frame];
    [self.videoControl setFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [self.videoControl setNeedsLayout];
    [self.videoControl layoutIfNeeded];
}

#pragma mark - 取出视频图片
+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}


@end
